package com.sgcc.activiti.service.impl;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.sgcc.activiti.domain.OInterfaceIndex;
import com.sgcc.activiti.service.IOInterfaceIndexService;
import com.sgcc.activiti.util.HttpsUrlValidator;
import com.sgcc.common.core.domain.R;
import com.sgcc.common.core.utils.FastJsonUtil;
import com.sgcc.common.core.utils.HttpClientUtil;
import com.sgcc.common.core.utils.StringUtils;
import com.sgcc.common.core.utils.file.MimeTypeUtils;
import com.sgcc.common.core.web.domain.AjaxResult;
import com.sgcc.common.security.service.TokenService;
import com.sgcc.system.api.model.LoginUser;
import net.bytebuddy.implementation.bytecode.Throw;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sgcc.activiti.mapper.OContentAdPicMapper;
import com.sgcc.activiti.domain.OContentAdPic;
import com.sgcc.activiti.service.IOContentAdPicService;
import sun.misc.BASE64Encoder;

/**
 * 广告图片Service业务层处理
 *
 * @author sgcc
 * @date 2021-04-07
 */
@Service
public class OContentAdPicServiceImpl implements IOContentAdPicService {
    private static final Logger logger = LoggerFactory.getLogger(OContentAdPicServiceImpl.class);
    @Autowired
    private OContentAdPicMapper oContentAdPicMapper;
    @Autowired
    private IOInterfaceIndexService interfaceIndexService;
    @Autowired
    private TokenService tokenService;

    /**
     * 查询广告图片
     *
     * @param id 广告图片ID
     * @return 广告图片
     */
    @Override
    public OContentAdPic selectOContentAdPicById(String id) {
        return oContentAdPicMapper.selectOContentAdPicById(id);
    }

    /**
     * 查询广告图片列表
     *
     * @param oContentAdPic 广告图片
     * @return 广告图片
     */
    @Override
    public List<OContentAdPic> selectOContentAdPicList(OContentAdPic oContentAdPic) {
        return oContentAdPicMapper.selectOContentAdPicList(oContentAdPic);
    }

    /**
     * 新增广告图片
     *
     * @param oContentAdPic 广告图片
     * @return 结果
     */
    @Override
    public int insertOContentAdPic(OContentAdPic oContentAdPic) {
        LoginUser loginUser = tokenService.getLoginUser();
        oContentAdPic.setCreateDate(new Date());
        oContentAdPic.setUpdateDate(new Date());
        oContentAdPic.setCreateBy(loginUser.getUserid());
        oContentAdPic.setUpdateBy(loginUser.getUserid());
        oContentAdPic.setDelFlag("0");
        String id= UUID.randomUUID().toString().replaceAll("-", "");
        oContentAdPic.setId(id);
        return oContentAdPicMapper.insertOContentAdPic(oContentAdPic);
    }

    /**
     * 修改广告图片
     *
     * @param oContentAdPic 广告图片
     * @return 结果
     */
    @Override
    public int updateOContentAdPic(OContentAdPic oContentAdPic) {
        LoginUser loginUser = tokenService.getLoginUser();
        oContentAdPic.setUpdateDate(new Date());
        oContentAdPic.setUpdateBy(loginUser.getUserid());
        return oContentAdPicMapper.updateOContentAdPic(oContentAdPic);
    }

    /**
     * 批量删除广告图片
     *
     * @param ids 需要删除的广告图片ID
     * @return 结果
     */
    @Override
    public int deleteOContentAdPicByIds(String[] ids) {
        return oContentAdPicMapper.deleteOContentAdPicByIds(ids);
    }

    /**
     * 删除广告图片信息
     *
     * @param id 广告图片ID
     * @return 结果
     */
    @Override
    public int deleteOContentAdPicById(String id) {
        return oContentAdPicMapper.deleteOContentAdPicById(id);
    }

    @Override
    public R<OContentAdPic> uploadImg(String picType, String url, String serviceType, String busiType) {
        logger.info("上传图片的URL：" + url);
        if (StringUtils.isBlank(url)) {
            return R.fail("没有url");
        }
        OContentAdPic adPic = new OContentAdPic();
//        String uploadImgRpcInterface = DictUtils.getDictValue("上传图片接口", "rpcInterface", "test");
//        String uploadImgRpcInterface = "test";
        OInterfaceIndex oInterfaceIndex = interfaceIndexService.selectAddressbycode("0101179");
        if (null == oInterfaceIndex || null == oInterfaceIndex.getInterfaceAdress()) {
            return R.fail("无法获取根据0101179图片上传地址！");
        }
        String[] split = url.split("/");
        String fileName = split[split.length - 1];
        // 对字节数组Base64编码
        String encodeData = HttpsUrlValidator.retrieveResponseFromServer(url);
        /**
         * 调用远程图片接口
         * uploadImgRpcInterface
         */
        String params = "";
        //构建参数
        Map paramsData = new HashMap();
        paramsData.put("areaNo", "35101");
        paramsData.put("busiType", busiType);
        paramsData.put("contractChannel", "01");
        paramsData.put("fileContent", encodeData);
        paramsData.put("fileName", fileName);
        paramsData.put("serviceType", serviceType);
        paramsData.put("storageBase", "inside");
        Map map = new HashMap();
        map.put("serviceCode", "0101296");
        map.put("source", "SGAPP");
        map.put("target", "35101");
        map.put("data", paramsData);
        params = FastJsonUtil.toJSONString(map);
        R<String> rpcResultStr = HttpClientUtil.sendJsonStr(oInterfaceIndex.getInterfaceAdress(), params);
        //解析返回值
        if (200 != rpcResultStr.getCode()) {
            return R.fail(oInterfaceIndex.getInterfaceAdress() + "接口调用失败！" + rpcResultStr.getCode());
        }
        R r = FastJsonUtil.toBean(rpcResultStr.getData(), R.class);
        int oContentAdResultCode = r.getCode();
        if (oContentAdResultCode == 1) {
            JSONObject data = (JSONObject) r.getData();
            //文件ID
            String fileId = data.getString("fileId");
            //文件名称
            String fileName2 = data.getString("fileName");
            //远程系统图片ID
            adPic.setPicId(fileId);
            //图片类型，01banner，02详情图片,03广告小图
            adPic.setPicType(picType);
            //本地图片路径
            adPic.setPicUrl(url);
            adPic.setRemarks(fileName2);
            this.insertOContentAdPic(adPic);
            return R.ok(adPic);
        }
        return R.fail("推送图片失败！");
    }


    private String getBase64(String url) {
        InputStream in = null;
        final ByteArrayOutputStream data = new ByteArrayOutputStream();
        //读取图片字节数组
        try {
            URL url2 = new URL(url);
            final byte[] by = new byte[1024];
            // 创建链接获取图片
            final HttpURLConnection conn = (HttpURLConnection) url2.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            in = conn.getInputStream();
            int len = -1;
            while ((len = in.read(by)) != -1) {
                data.write(by, 0, len);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        //返回Base64编码过的字节数组字符串
        String encode = encoder.encode(data.toByteArray());
//        String[] split = url.split(".");
//        String head = "data:image/" + split[split.length - 1] + ";base64,";
        encode = encode.replaceAll("[\\s*\t\n\r]", "");
        return encode;
    }
}
